package com.cskaoyan.gateway.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.gateway.cache.CacheManager;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IUserService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Description: 用户模块
 * @Author: 徐能雄
 * @Date: 2021/9/28 20:55
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Reference(timeout = 30000, check = false)
    IKaptchaService iKaptchaService;

    @Reference(timeout = 30000, check = false)
    IUserService iUserService;
    @Autowired
    CacheManager cacheManager;

    /**
     * 1、用户注册
     */
    @PostMapping("/register")
    @Anoymous
    public ResponseData register(@RequestBody Map<String, String> map, HttpServletRequest request) {

        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        String email = map.get("email");

        //验证验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request,"kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        //验证码错误，返回提示信息
        if(!validateCode(kaptchaCodeRequest)){
            return new ResponseUtil<>().setErrorMsg(SysRetCodeConstants.KAPTCHA_CODE_ERROR.getMessage());
        }

        //验证码正确，继续注册
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setUserName(userName);
        userRegisterRequest.setUserPwd(userPwd);
        userRegisterRequest.setEmail(email);
        UserRegisterResponse response = iUserService.register(userRegisterRequest);
        if(!SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(null);
    }

    /**
     * 2、用户登录
     */
    @PostMapping("/login")
    @Anoymous
    public ResponseData loginPost(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {



        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");

        //判断验证码是否正确
        String uuid = CookieUtil.getCookieValue(request,"kaptcha_uuid");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        //验证码错误，返回提示信息
        if(!validateCode(kaptchaCodeRequest)){
            return new ResponseUtil<>().setErrorMsg(SysRetCodeConstants.KAPTCHA_CODE_ERROR.getMessage());
        }

        //验证码正确，继续对比用户信息
        UserLoginRequest userLoginRequest = new UserLoginRequest();
        userLoginRequest.setUserName(userName);
        userLoginRequest.setPassword(userPwd);
        UserLoginResponse userLoginResponse = iUserService.login(userLoginRequest);
        if(!SysRetCodeConstants.SUCCESS.getCode().equals(userLoginResponse.getCode())) {
            return new ResponseUtil<>().setErrorMsg(userLoginResponse.getMsg());
        }

        //登录成功,设置cookie
        Cookie cookie = CookieUtil.genCookie("access_token", userLoginResponse.getToken(), "/", 60*60);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
        Cookie[] cookies = request.getCookies();
        String verify = "";
        for (Cookie cookie1 : cookies) {
            if(cookie1.getName().equals("kaptcha_uuid")){
                verify = cookie1.getValue();
            }
        }
        if(!StringUtils.isEmpty(verify)){
            cacheManager.setCache(userName,verify,1);
        }

        return new ResponseUtil<>().setData(userLoginResponse);
    }

    /**
     * 3、用户验证
     */
    @GetMapping("/login")
    public ResponseData loginGet(HttpServletRequest request) {

        String attribute = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject jsonObject = JSON.parseObject(attribute);
        String username = (String) jsonObject.get("username");
        Cookie[] cookies = request.getCookies();
        String verify = "";
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("kaptcha_uuid")){
                verify = cookie.getValue();
            }
        }
        String s = cacheManager.checkCache(username);
        if(!verify.equals(s)){
            return new ResponseUtil<>().setErrorMsg("用户已在别的位置登录！");

        }

        try {
            JSONObject map = JSON.parseObject(attribute);
            return new ResponseUtil<>().setData(map);
        }catch (Exception e){
            return new ResponseUtil<>().setErrorMsg("token已失效");
        }
    }

    /**
     * 4、用户退出
     */
    @GetMapping("/loginOut")
    public ResponseData loginOut(HttpServletRequest request, HttpServletResponse response) {

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if("access_token".equals(cookie.getName())) {
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        String tokenStr = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        // fastjson的方法，是将str转化为相应的JSONObject对象，
        // 其中str是“键值对”形式的json字符串，转化为JSONObject对象之后就可以使用其内置的方法，进行各种处理
        JSONObject jsonObject = JSON.parseObject(tokenStr);
        String username = (String) jsonObject.get("username");
        cacheManager.expire(username,0);
        return new ResponseUtil<>().setData(null);
    }


    /**
     * 5、用户激活
     */
    @GetMapping("/verify")
    @Anoymous
    public ResponseData verify(String userName, String uid) {

        UserVerifyRequest userVerifyRequest = new UserVerifyRequest();
        userVerifyRequest.setUserName(userName);
        userVerifyRequest.setUuid(uid);

        UserVerifyResponse userVerifyResponse = iUserService.verify(userVerifyRequest);
        if(!SysRetCodeConstants.SUCCESS.getCode().equals(userVerifyResponse.getCode())) {
            return new ResponseUtil<>().setErrorMsg(userVerifyResponse.getMsg());
        }
        return new ResponseUtil<>().setData(null);
    }



    /**
     * 判断验证码是否正确
     * true表示正确，false表示错误
     */
    private boolean validateCode(KaptchaCodeRequest request) {
        KaptchaCodeResponse response = iKaptchaService.validateKaptchaCode(request);
        return SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode());
    }

}
